import React, {DragEvent, FC, useState} from 'react';
import Row from "./components/Row";
import Column from "./components/Column";
import Flex from "./components/Flex";
import Header from "./components/Header";
import Title from "./components/Title";
import Description from "./components/Description";
import {closest} from "./utils";


const widgets: { [key: string]: FC<any> } = {
  Flex, Row, Column, Title, Header, Description,
}

const SelectWidget = ({ data, children, index }: any) => {
  const $$customise: any = {};
  if (data.customises?.length) {
    data.customises.forEach((item: any, idx: number) => {
      // console.log('Playground.customises: => ', item.name);
      $$customise[item.name] = (props: any) => <SelectWidget {...props} data={item}  index={[...index, idx]}/>
    })
  }

  const CustomComp = widgets[data.name]
  // console.log('Playground.customises: => ', data.name)
  if (CustomComp) {
    const props = data.defaultProps || {}
    return (
      <CustomComp {...props } { ...$$customise } index={index}>
        { children }
      </CustomComp>
    )
  } else return null
}

const Playground = ({ data }: any) => {

  const __onDrop = (event: DragEvent <HTMLElement>) => {
    event.preventDefault();
    event.stopPropagation();
    const node = closest(event.nativeEvent.target as HTMLElement, 'droppable');
    const transfer = event.dataTransfer.getData('drag:data');

    console.log('event', transfer, (event.nativeEvent.target as HTMLElement).classList)
    console.log('event', transfer, (event.nativeEvent.target as HTMLElement).classList.contains('sortable'))
    if (!transfer) return

    try {
      const dataTransfer: { index: string, data: any } = JSON.parse(transfer);
      // 提交数据
      const data = {
        // 目标位置
        nextIndex: node?.dataset.index,
        // 来源位置
        prevIndex: dataTransfer.index,
        data: dataTransfer.data
      }
    } catch (error) {
      return console.log(error)
    } finally {
      // 清空拖拽的数据
      event.dataTransfer.clearData();
    }
  }

  const __onDragOver = (ev: DragEvent <HTMLElement>) => {
    ev.preventDefault(); // Allow the drop
  }

  console.log('data', data)

  return (
    <div
      className="playground"
      onDragOver={__onDragOver}
      onDrop={__onDrop}
    >
      {
        data.map((item: any, index: number) => (
          <SelectWidget data={item} key={index} index={[index]} />
        ))
      }
    </div>
  )
}

export default Playground;
